package com.example.netty.server.tcp;

import com.example.netty.server.coder.decoder.DecoderUtils;
import com.example.netty.server.coder.encoder.EncoderUtils;
import com.example.netty.service.CallBack;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TcpServer {

    private final static Logger logger = LoggerFactory.getLogger(TcpServer.class);

    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workGroup;
    private final BlockingQueue<ChannelHandlerContext> queue;


    public TcpServer(String ip, int port, String coderType, int maxConnect, CallBack callBack) {
        this.bossGroup = new NioEventLoopGroup();
        this.workGroup = new NioEventLoopGroup();
        this.queue = new ArrayBlockingQueue<>(maxConnect);

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("decoder", DecoderUtils.getInstance(coderType));
                        socketChannel.pipeline().addLast("encoder", EncoderUtils.getInstance(coderType));
                        socketChannel.pipeline().addLast(new TcpServerHandler(queue, callBack));
                    }
                });
        ChannelFuture channelFuture = bootstrap.bind(ip, port);
        try {
            Channel serverChannel = channelFuture.sync().channel();
            //注册连接事件监听器
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    logger.info("服务端{}:{}创建成功，ID:{}", ip, port, serverChannel.id());
                } else {
                    logger.info("服务端{}:{}创建失败，ID:{}", ip, port, serverChannel.id());
                }
            });
            //注册关闭事件监听器
            serverChannel.closeFuture().addListener(cfl -> {
                logger.info("服务端{}:{}已关闭，ID:{}", ip, port, serverChannel.id());
            });
        } catch (Exception e) {
            close();
            logger.warn("", e);
        }
    }

    public void close() {
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        queue.clear();
    }
}
